# Knife.gd - Simple projectile weapon
class_name KnifeWeapon
extends BaseWeapon

# Weapon Specifics - Load prefab from WeaponData
@export var projectile_scene: PackedScene = preload("res://scenes/weapons/projectiles/KnifeProjectile.tscn")
# @export var projectile_speed: float = 400.0

# Special Upgrades
var pierce_count: int = 0 # How many enemies it can pierce
var bounce_count: int = 0 # How many times it can bounce

func _ready():
	# Inherits _ready from BaseWeapon, Timer is set up there
	pass

func perform_attack():
	# Override base perform_attack
	if not player_node or not projectile_scene:
		printerr("KnifeWeapon: Player or Projectile Scene not set!")
		if cooldown > 0 and cooldown_timer.is_stopped(): cooldown_timer.start() # Still restart timer
		return

	var enemies_to_target = quantity
	var potential_targets = find_nearby_enemies(range) # Get potential targets

	if potential_targets.is_empty():
		# No enemies in range, maybe fire straight? Or just wait.
		# print("Knife: No target in range.")
		pass # Don't fire if no target? Or fire forward?
	else:
		# Fire 'quantity' projectiles at 'quantity' nearest enemies
		for i in range(min(enemies_to_target, potential_targets.size())):
			var target_enemy = potential_targets[i]
			if is_instance_valid(target_enemy):
				var projectile = projectile_scene.instantiate() as KnifeProjectile
				if projectile:
					# Get projectile container node (e.g., child of MainGame or Level)
					var proj_container = get_tree().get_first_node_in_group("projectile_container")
					if proj_container: proj_container.add_child(projectile)
					else: get_tree().current_scene.add_child(projectile) # Fallback

					var direction = player_node.global_position.direction_to(target_enemy.global_position)
					projectile.global_position = player_node.global_position # Start at player
					projectile.rotation = direction.angle()
					projectile.initialize(damage, direction, pierce_count, bounce_count) # Pass relevant stats
					print("Fired knife at ", target_enemy.name)
				else:
					printerr("Failed to instance KnifeProjectile")

	# Restart cooldown timer AFTER firing logic
	if cooldown > 0 and cooldown_timer.is_stopped():
		cooldown_timer.start()


func find_nearby_enemies(search_range: float) -> Array[Node2D]:
	var nearby_enemies: Array[Node2D] = []
	var enemies = get_tree().get_nodes_in_group("enemies")
	for enemy in enemies:
		if is_instance_valid(enemy) and enemy.has_method("is_dying") and not enemy.is_dying:
			if player_node.global_position.distance_squared_to(enemy.global_position) < search_range * search_range:
				nearby_enemies.append(enemy)

	# Sort by distance (nearest first)
	nearby_enemies.sort_custom(func(a, b):
		var dist_a = player_node.global_position.distance_squared_to(a.global_position)
		var dist_b = player_node.global_position.distance_squared_to(b.global_position)
		return dist_a < dist_b
	)
	return nearby_enemies


func _apply_special_upgrade(upgrade: WeaponUpgrade):
	# Example implementation for knife specials
	if "pierce" in upgrade.description.to_lower():
		pierce_count += int(upgrade.value_change) if upgrade.value_change > 0 else 1
		print("Knife pierce count now:", pierce_count)
	elif "bounce" in upgrade.description.to_lower():
		bounce_count += int(upgrade.value_change) if upgrade.value_change > 0 else 1
		print("Knife bounce count now:", bounce_count)
